/*
 * @Author: hc
 * @Date: 2024-02-29 20:10:03
 * @LastEditTime: 2024-03-28 10:11:36
 * @LastEditors: hc
 * @Description: 打开表达式model
 */
import { message, showModal } from '../../functionalComponent';
import { getGlobalConfig, iup } from '../../util';
import ExpressModal from './base';
import { OpenExpressModelParams, ValueType } from './types';

export const openExpressModel = (params: OpenExpressModelParams) =>
  new Promise<ValueType | null>((resolve) => {
    const {
      bizPoint,
      value,
      definitionRequest,
      definitionVersionRequest,
      dataModelRequest,
      earlyWarningRequest,
      onOk,
      onCancel
    } = params;

    const { height, width } = getGlobalConfig().default.helpConfig;

    const configMap = [
      {
        bizPoint: 'ruleDefinition',
        type: 'definitionRequest',
        params: definitionRequest
      },
      {
        bizPoint: 'ruleDefinitionVersion',
        type: 'definitionVersionRequest',
        params: definitionVersionRequest
      },
      {
        bizPoint: 'dataModelDesign',
        type: 'dataModelRequest',
        params: dataModelRequest
      },
      {
        bizPoint: 'earlyWarning',
        type: 'earlyWarningRequest',
        params: earlyWarningRequest
      }
    ] as const;

    const config = configMap.find((v) => v.bizPoint === bizPoint)!;

    showModal({
      title: '表达式',
      height,
      width,
      contentStyle: { padding: '0px 16px' },
      content: (
        <ExpressModal
          type={{
            type: config?.type,
            // @ts-ignore
            value: {
              [config.type]: config?.params,
              bizPoint: bizPoint
            }
          }}
          value={value}
        />
      ),
      async onOk(ins) {
        const { getValue } = ins.getApi();
        const res = await getValue();
        if (!res.validateResult) {
          message.warn(res.validateMsg);
          return;
        }

        const value: ValueType = {
          label: res.expressionDisplay,
          value: res.expressionValue,
          origin: res
        };
        if (onOk) onOk(value);
        resolve(value);
        ins.destroy();
      },
      onCancel(ins) {
        if (onCancel) onCancel();
        resolve(null);
        ins.destroy();
      }
    });
  });

iup.registerExternal({ openExpressModel });
